package com.syqc.monitor.ui.newaddcar

import android.Manifest
import android.app.Activity
import android.view.WindowManager
import androidx.activity.viewModels
import androidx.core.view.isVisible
import androidx.recyclerview.widget.GridLayoutManager
import autodispose2.autoDispose
import com.luck.picture.lib.entity.LocalMedia
import com.permissionx.guolindev.PermissionX
import com.syqc.choose.team.ChooseTeamActivity
import com.syqc.choose.teamcar.TeamsActivity
import com.syqc.comlib.base.BaseBarActivity
import com.syqc.comlib.rx.doAfterChanged
import com.syqc.comlib.rx.filterFast
import com.syqc.comlib.utils.ActivityResultUtil.launchAct
import com.syqc.comlib.utils.ActivityResultUtil.registerResult
import com.syqc.comlib.utils.ActivityResultUtil.registerResultOk
import com.syqc.comlib.utils.GsonUtil
import com.syqc.comlib.utils.ToolbarHelper
import com.syqc.comlib.utils.showToast
import com.syqc.comlib.utils.toast
import com.syqc.entity.KeyValue
import com.syqc.entity.TmnManager
import com.syqc.monitor.R
import com.syqc.monitor.databinding.ActivityAddCarNewBinding
import com.syqc.monitor.databinding.IncludeSelectSureBinding
import com.syqc.monitor.ui.ScanQrExteActivity
import com.syqc.monitor.ui.tmn.ChooseTmnActivity
import com.syqc.utils.Keys
import com.syqc.utils.NetDataUtil
import com.syqc.utils.isNumChar
import com.syqc.utils.setDescStar
import com.syqc.utils.setInputChat
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers

/**
 *@author joker
 *@time   2024/3/11 9:34
 *@desc
 */
class AddCarActivity :
    BaseBarActivity<ActivityAddCarNewBinding>(ActivityAddCarNewBinding::inflate) {
    private var isCar = true
    private lateinit var mSureVB: IncludeSelectSureBinding
    private val mPhotoPopup by lazy { PhotoImagePopup(this, 1, this::callback) }
    private val mPhotoView by lazy { PhotoViewPopup(this) }
    private val mKeyValuePopup by lazy { KeyValuePopup(this) }

    private val mAdapter by lazy { PhotoCarTmnAdapter() }
    private val mTmnAdapter by lazy { PhotoCarTmnAdapter() }
    private val mViewModel by viewModels<AddNewCarViewModel>()

    private val mVideoPopup by lazy {
        PopupVideoPass(this) {
            mViewModel.videoChannel = it
        }
    }

    override fun initView() {
        mSureVB = IncludeSelectSureBinding.bind(binding.root)
        binding.lrTvPlateColor.setStartTitle(getString(R.string.desc_plate_color))
        binding.lrTvChooseTeam.setStartTitle(getString(R.string.desc_com_choose_team))

        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN)
        ToolbarHelper.setToolbar(this, R.string.title_other_add)
        mSureVB.tvSure.setText(R.string.desc_com_sure)
        mViewModel.toastObserver()
            .observeOn(AndroidSchedulers.mainThread())
            .autoDispose(scopeProvider).subscribe(this::toastObserver)

        binding.seePlate.getEndEditText().setInputChat(50, true)

        binding.uetSimCode.setDescStar(getString(R.string.desc_sim_num))

        binding.recyclerCar.layoutManager = GridLayoutManager(this, 4)
        binding.recyclerCar.adapter = mAdapter

        binding.recyclerTmn.layoutManager = GridLayoutManager(this, 4)
        binding.recyclerTmn.adapter = mTmnAdapter

        mViewModel.colorLive.observe(this) {
            binding.lrTvPlateColor.setRightText(it.value)
        }

        mViewModel.handlePhoto(null)
        mViewModel.photoLive.observe(this) {
            mAdapter.setList(it)
            mAdapter.notifyDataSetChanged()
        }

        mViewModel.handleTmnPhoto(null)
        mViewModel.photoTmnLive.observe(this) {
            mTmnAdapter.setList(it)
            mTmnAdapter.notifyDataSetChanged()
        }

        mViewModel.tmnsLive.observe(this) {
            if (!it.isNullOrEmpty()) {
                tmnLauncher.launchAct<ChooseTmnActivity>(this) {
                    putExtra(Keys.INTENT_TEAM_ID, mViewModel.teamId)
                }
            }
        }
    }


    override fun setListener() {
        binding.seePlate.getEndEditText().doAfterChanged {
            mViewModel.carPlate = it
        }
        binding.uetCarName.getEditText().doAfterChanged {
            mViewModel.carName = it
        }

        binding.editTmnCode.doAfterChanged {
            mViewModel.tmnNum = it
        }

        binding.uetSimCode.setOnTextChange {
            mViewModel.simNum = it
        }

        binding.editVideo.doAfterChanged {
            if (it.isNotEmpty() && it.toInt() > 32) {
                binding.editVideo.setText("32")
                mViewModel.videoPass = "32"
                binding.editVideo.setSelection(binding.editVideo.text.length)
            } else {
                mViewModel.videoPass = it
            }
            if (mViewModel.videoPass.isEmpty()) return@doAfterChanged
            mViewModel.videoChannel = null
            VideoPassUtil.setPassNum(mViewModel.videoPass.toInt())
        }

        binding.ivVideoSet.filterFast {
            if (mViewModel.videoPass.isEmpty()) {
                showToast(R.string.hint_toast_video_pass)
                return@filterFast
            }
            if (mViewModel.videoPass.toInt() == 0) return@filterFast
            mVideoPopup.showView(
                window.decorView,
                binding.editVideo.text.toString().toInt(),
                mViewModel.videoChannel
            )

        }
        binding.uetDefine.setOnTextChange {
            mViewModel.tmnKey = it
        }

        binding.lrTvChooseTeam.filterFast {
            if (NetDataUtil.isSyncTree) {
                teamLauncher.launchAct<TeamsActivity>(this) {
                    putExtra("isChoose", true)
                }
            } else {
                teamLauncher.launchAct<ChooseTeamActivity>(this) {
                    putExtra("isChoose", true)
                }
            }
        }

        binding.lrTvPlateColor.setOnClickListener {
            mKeyValuePopup.showAtLocation(
                window.decorView,
                R.string.desc_car_color,
                mViewModel.colorList,
                mViewModel.colorIndex
            )
        }

        mKeyValuePopup.setCallBack(object : KeyValuePopup.CallBack {
            override fun onBack(entity: KeyValue, index: Int) {
                mViewModel.colorIndex = index
                mViewModel.colorId = entity.key
                binding.lrTvPlateColor.setRightText(entity.value)

            }
        })

        binding.ivScan.filterFast {
            getCameraPermission()
        }

        mSureVB.tvSure.filterFast {
            mViewModel.addNewCar()
        }
        binding.rdgType.setOnCheckedChangeListener { group, checkedId ->
            when (checkedId) {
                R.id.rdbSim -> {
                    mViewModel.keyType = "1"
                    binding.uetDefine.isVisible = false
                    binding.uetDefine.setDesc(getString(R.string.desc_com_define))
                    binding.uetSimCode.setDescStar(getString(R.string.desc_sim_num))
                    binding.tvTmnNum.text = getString(R.string.desc_tmn_num)

                }

                R.id.rdbTmn -> {
                    mViewModel.keyType = "2"
                    binding.uetDefine.isVisible = false
                    binding.uetDefine.setText(getString(R.string.desc_com_define))
                    binding.uetSimCode.setDesc(getString(R.string.desc_sim_num))
                    binding.tvTmnNum.text = setDescStar(getString(R.string.desc_tmn_num))
                }

                R.id.rdbDefine -> {
                    mViewModel.keyType = "3"
                    binding.uetDefine.isVisible = true
                    binding.uetDefine.setDescStar(getString(R.string.desc_com_define))
                    binding.uetSimCode.setDesc(getString(R.string.desc_sim_num))
                    binding.tvTmnNum.text = getString(R.string.desc_tmn_num)
                }
            }
            binding.uetDefine.setText("")
        }


        binding.uetOwnerName.setOnTextChange {
            mViewModel.owner = it
        }

        binding.uetOwnerPhone.setOnTextChange {
            mViewModel.ownerPhone = it
        }

        binding.editDesc.doAfterChanged {
            mViewModel.des = it
        }

        binding.tvInputTmn.setOnClickListener {
            mTmnAdapter.isSee = false
            mViewModel.resetInfo()
            resetTmn()
            mViewModel.isChooseTmn = false
            binding.tvChooseTmn.isSelected = false
            mViewModel.isInputTmn = !mViewModel.isInputTmn
            if (mViewModel.isInputTmn) {
                mViewModel.keyType = "1"
            } else {
                mViewModel.keyType = ""
            }
            binding.tvInputTmn.isSelected = mViewModel.isInputTmn
            binding.llTmn.isVisible = mViewModel.isInputTmn
            setEnable(true)
        }

        binding.tvChooseTmn.setOnClickListener {
            mViewModel.resetInfo()
            resetTmn()
            if (!mViewModel.isChooseTmn && mViewModel.teamId.isEmpty()) {
                showToast(R.string.toast_choose_team)
                return@setOnClickListener
            }
            mViewModel.isInputTmn = false
            binding.llTmn.isVisible = false
            binding.tvInputTmn.isSelected = false
            if (mViewModel.isChooseTmn) {
                mViewModel.isChooseTmn = false
                binding.tvChooseTmn.isSelected = false
            } else {
                mViewModel.getTmnByTeam()
            }
        }

        mAdapter.setOnItemClickListener { _, _, position ->
            val path = mAdapter.data[position]
            if (path.isEmpty()) {
                isCar = true
                mPhotoPopup.showAtLocation(mViewModel.nowCarNum)
            } else {
                mPhotoView.show(path)
            }
        }

        mAdapter.setOnItemChildClickListener { _, _, position ->
            mViewModel.removePhoto(position)
        }

        mTmnAdapter.setOnItemClickListener { _, _, position ->
            val path = mTmnAdapter.data[position]
            if (mTmnAdapter.isSee) {
                if (path.isEmpty()) return@setOnItemClickListener
                mPhotoView.show(path)
            } else {
                if (path.isEmpty()) {
                    isCar = false
                    mPhotoPopup.showAtLocation(mViewModel.nowTmnNum)
                } else {
                    mPhotoView.show(path)
                }
            }
        }

        mTmnAdapter.setOnItemChildClickListener { _, _, position ->
            mViewModel.removeTmnPhoto(position)
        }
    }

    private fun resetTmn() {
        binding.rdbSim.isChecked = true
        binding.uetDefine.setText("")
        binding.uetSimCode.setText("")
        binding.editTmnCode.setText("")
        binding.uetDefine.isVisible = false
    }


    private fun getCameraPermission() {
        PermissionX.init(this).permissions(Manifest.permission.CAMERA)
            .request { allGranted, _, _ ->
                if (allGranted) {
                    launcher.launchAct<ScanQrExteActivity>(this@AddCarActivity)
                } else {
                    getString(R.string.toast_persission_set).toast(this@AddCarActivity)
                }
            }
    }

    private val teamLauncher = registerResultOk { result ->
        result.data?.let {
            val teamId = it.getStringExtra(Keys.INTENT_TEAM_ID) ?: ""
            val teamName = it.getStringExtra(Keys.INTENT_TEAM_NAME) ?: ""
            mViewModel.teamId = teamId
            binding.lrTvChooseTeam.setRightText(teamName)
        }
    }

    private fun callback(type: Int, result: ArrayList<LocalMedia>?) {
        if (isCar) {
            mViewModel.handlePhoto(result)
        } else {
            mViewModel.handleTmnPhoto(result)
        }
    }

    private val launcher = registerResult() { result ->
        if (result.resultCode == Activity.RESULT_OK) {
            result.data?.let {
                val string = it.getStringExtra("ScanResult") ?: ""
                if (string.isNumChar()) {
                    binding.editTmnCode.setText(string)
                } else {
                    showToast(R.string.toast_scan_sure_qr)
                }
            }
        }
    }

    private val tmnLauncher = registerResultOk {
        it.data?.run {
            val tmnManager = getStringExtra(Keys.INTENT_DATA) ?: ""
            if (tmnManager.isNotEmpty()) {
                setEnable(false)
                binding.llTmn.isVisible = true
                mViewModel.isChooseTmn = true
                binding.tvChooseTmn.isSelected = true

                GsonUtil.formObject<TmnManager>(tmnManager).run {
                    mViewModel.tmnId = tmnId
                    mViewModel.keyType = keyType
                    when (keyType) {
                        "1" -> {
                            binding.rdbSim.isChecked = true
                        }

                        "2" -> {
                            binding.rdbTmn.isChecked = true
                        }

                        "3" -> {
                            binding.rdbDefine.isChecked = true
                            binding.uetDefine.isVisible = true
                        }
                    }
                    binding.uetDefine.setText(tmnKey)
                    binding.uetSimCode.setText(simCard)
                    binding.editTmnCode.setText(tmnNo)
                    mTmnAdapter.isSee = true
                    mViewModel.handleTmnUrlPhoto(pics)
                }
            }
        }
    }

    //是否可编辑
    private fun setEnable(isEnable: Boolean) {
        binding.rdbSim.isEnabled = isEnable
        binding.rdbTmn.isEnabled = isEnable
        binding.rdbDefine.isEnabled = isEnable
        binding.editTmnCode.isEnabled = isEnable
        binding.ivScan.isEnabled = isEnable
        binding.uetSimCode.getEditText().isEnabled = isEnable
        binding.uetDefine.isEnabled = isEnable
    }
}